import { useState, useEffect } from 'react';
import { 
  Form, 
  Upload, 
  Button, 
  Select, 
  Card, 
  message, 
  Space, 
  Typography 
} from 'antd';
import { UploadOutlined, TranslationOutlined } from '@ant-design/icons';
import type { UploadFile } from 'antd/es/upload/interface';
import { translateFile } from '../services/api';

const { Option } = Select;
const { Title } = Typography;

interface TranslationFormProps {
  onTranslationStart: () => void;
  onTranslationComplete: (result: any) => void;
  onTranslationError: () => void;
}

const TranslationForm: React.FC<TranslationFormProps> = ({
  onTranslationStart,
  onTranslationComplete,
  onTranslationError
}) => {
  const [form] = Form.useForm();
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [uploading, setUploading] = useState(false);
  const [sourceLanguage, setSourceLanguage] = useState<string>('zh');
  const [targetLanguages, setTargetLanguages] = useState<string[]>([]);

  // 支持的语言列表
  const languages = [
    { code: 'zh', name: '中文' },
    { code: 'en', name: '英文' },
    { code: 'ja', name: '日文' },
    { code: 'ko', name: '韩文' },
    { code: 'fr', name: '法文' },
    { code: 'de', name: '德文' },
    { code: 'es', name: '西班牙文' },
    { code: 'ru', name: '俄文' },
    // 可以添加更多语言
  ];

  // 当源语言改变时，清除目标语言中与源语言相同的选项
  useEffect(() => {
    if (targetLanguages.includes(sourceLanguage)) {
      const newTargetLanguages = targetLanguages.filter(lang => lang !== sourceLanguage);
      setTargetLanguages(newTargetLanguages);
      form.setFieldsValue({ targetLanguages: newTargetLanguages });
    }
  }, [sourceLanguage, form]);

  const handleSourceLanguageChange = (value: string) => {
    setSourceLanguage(value);
  };

  const handleTargetLanguagesChange = (values: string[]) => {
    // 过滤掉与源语言相同的选项
    const filteredValues = values.filter(lang => lang !== sourceLanguage);
    setTargetLanguages(filteredValues);
    
    // 如果过滤后的值与原始选择不同，更新表单值
    if (filteredValues.length !== values.length) {
      form.setFieldsValue({ targetLanguages: filteredValues });
      message.info('目标语言不能包含源语言');
    }
  };

  const handleUpload = async () => {
    const values = await form.validateFields();
    const { sourceLanguage, targetLanguages } = values;
    
    if (fileList.length === 0) {
      message.error('请先上传文件');
      return;
    }
    
    const formData = new FormData();
    
    // 处理文件上传
    const file = fileList[0];
    // 对于Ant Design的Upload组件，文件可能在originFileObj或者raw属性中
    if (file.originFileObj) {
      formData.append('file', file.originFileObj);
    } else if ((file as any).raw) {
      formData.append('file', (file as any).raw);
    } else {
      // 模拟一个空文件，用于演示
      const emptyFile = new File([''], file.name || 'sample.xlsx', { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      formData.append('file', emptyFile);
    }
    
    formData.append('sourceLanguage', sourceLanguage);
    formData.append('targetLanguages', JSON.stringify(targetLanguages));
    
    setUploading(true);
    onTranslationStart();
    
    try {
      const result = await translateFile(formData);
      message.success('翻译成功！');
      onTranslationComplete(result);
    } catch (error) {
      message.error('翻译失败，请重试！');
      onTranslationError();
    } finally {
      setUploading(false);
    }
  };

  const props = {
    onRemove: () => {
      setFileList([]);
    },
    beforeUpload: (file: any) => {
      // 检查文件类型
      const isExcel = 
        file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
        file.type === 'application/vnd.ms-excel' ||
        file.name.endsWith('.xlsx') ||
        file.name.endsWith('.xls') ||
        file.name.endsWith('.csv');
      
      if (!isExcel) {
        message.error('只能上传Excel或CSV文件！');
        return Upload.LIST_IGNORE;
      }
      
      // 确保文件对象可以被正确处理
      const newFile = {
        ...file,
        originFileObj: file,
        name: file.name, // 确保文件名被正确设置
        uid: file.uid || Date.now().toString(), // 确保有唯一ID
        status: 'done', // 设置状态为已完成
      };
      
      setFileList([newFile]);
      return false;
    },
    fileList,
    showUploadList: {
      showRemoveIcon: true,
      showDownloadIcon: false,
    },
  };

  return (
    <Card title="翻译配置" style={{ marginBottom: 24 }}>
      <Form
        form={form}
        layout="vertical"
        initialValues={{ sourceLanguage: 'zh' }}
      >
        <Form.Item
          name="sourceLanguage"
          label="源语言"
          rules={[{ required: true, message: '请选择源语言！' }]}
        >
          <Select 
            placeholder="选择源语言"
            onChange={handleSourceLanguageChange}
          >
            {languages.map(lang => (
              <Option key={lang.code} value={lang.code}>{lang.name}</Option>
            ))}
          </Select>
        </Form.Item>
        
        <Form.Item
          name="targetLanguages"
          label="目标语言"
          rules={[{ required: true, message: '请选择至少一种目标语言！' }]}
        >
          <Select 
            mode="multiple" 
            placeholder="选择目标语言（可多选）"
            optionFilterProp="children"
            onChange={handleTargetLanguagesChange}
            value={targetLanguages}
          >
            {languages
              .filter(lang => lang.code !== sourceLanguage)
              .map(lang => (
                <Option key={lang.code} value={lang.code}>{lang.name}</Option>
              ))
            }
          </Select>
        </Form.Item>
        
        <Form.Item
          name="file"
          label="上传文件"
          rules={[{ required: true, message: '请上传Excel或CSV文件！' }]}
        >
          <Upload 
            {...props} 
            maxCount={1}
            listType="text"
          >
            <Button icon={<UploadOutlined />}>选择文件</Button>
          </Upload>
        </Form.Item>
        
        <Form.Item>
          <Button
            type="primary"
            onClick={handleUpload}
            loading={uploading}
            icon={<TranslationOutlined />}
            disabled={fileList.length === 0}
          >
            开始翻译
          </Button>
        </Form.Item>
      </Form>
      
      <div style={{ marginTop: 16 }}>
        <Title level={5}>文件格式说明：</Title>
        <p>请上传包含以下列的Excel或CSV文件：</p>
        <ul>
          <li><strong>key</strong>: 翻译键名（必需）</li>
          <li><strong>源语言列</strong>: 对应源语言的文本内容</li>
        </ul>
      </div>
    </Card>
  );
};

export default TranslationForm;